<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace builder\helper;

use yii\helpers\ArrayHelper;

/**
 * 数组
 * @author cleverstone
 * @since ym2.0
 */
class Arr extends ArrayHelper
{
    /**
     * 数组或对象转XML
     * @param array|object $data
     * @return string
     */
    public static function toXml($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        $xml = '';
        foreach ($data as $key => $val) {
            if (is_null($val)) {
                $xml .= "<$key/>" . PHP_EOL;
            } else {
                if (!is_numeric($key)) {
                    $xml .= "<$key>";
                }

                $xml .= (is_array($val) || is_object($val)) ? self::toXml($val) : $val;
                if (!is_numeric($key)) {
                    $xml .= "</$key>" . PHP_EOL;
                }
            }
        }

        return '<xml>' . PHP_EOL . $xml . '</xml>';
    }
}